package is.progetto1.aritmeticExpression;

public final class Visitor {
	
	public String visitInfix(Expression e) {
		StringBuilder sb=new StringBuilder();
		sb.append("{");
		this.visitI(e,sb);
		sb.append("}");
		return sb.toString();
	}

	private void visitI(Expression e, StringBuilder sb) {
		if(e instanceof Operator){
			Operator o=(Operator)e;
			if(o!=null){
			sb.append("(");
			visitI(o.getLeft(),sb);
			sb.append(" "+o.getOperator()+" ");
			visitI(o.getRight(),sb);
			sb.append(")");
			}
		}
		if(e instanceof Variable){
			Variable v=(Variable)e;
			if(v!=null){
				sb.append(v.getName());
			}
		}
		if(e instanceof IntegerNoSign){
			IntegerNoSign i=(IntegerNoSign)e;
			if(i!=null){
				sb.append(i.getValue());	
			}
		}
	}

	public String visitPostfix(Expression e) {
		StringBuilder sb=new StringBuilder();
		sb.append("{");
		this.visitP(e,sb);
		sb.append("}");
		return sb.toString();
	}

	private void visitP(Expression e, StringBuilder sb) {
		if(e instanceof Operator){
			Operator o=(Operator)e;
			if(o!=null){
			sb.append("(");
			visitP(o.getLeft(),sb);
			visitP(o.getRight(),sb);
			sb.append(o.getOperator());
			sb.append(")");
			}
		}
		if(e instanceof Variable){
			Variable v=(Variable)e;
			if(v!=null){
				sb.append(v.getName()+" ");
			}
		}
		if(e instanceof IntegerNoSign){
			IntegerNoSign i=(IntegerNoSign)e;
			if(i!=null){
				sb.append(i.getValue()+" ");
			}
		}
	}

}
